package StudyCode.summary.BufferAndChannel;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class LockingChannelFile {
	public static void main(String[] args) throws Exception {
		Path path = Paths.get("E:\\Copy", "1.txt");
		ByteBuffer buffer = ByteBuffer.wrap("Locking Channel File".getBytes());
		try (FileChannel fileChannel = (FileChannel.open(path, EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE)))) {
			FileLock lock = fileChannel.lock();
			if (lock.isValid()) {
				System.out.println("向加锁文件写入 ...");
				Thread.sleep(2000);
				fileChannel.position(0);
				fileChannel.write(buffer);
				Thread.sleep(2000);
			}
			lock.release();
			System.out.println("\n释放锁!");
		} catch (IOException ex) {
			System.err.println(ex);
		}
	}
}
